/**
 * CopyRight © 2012 USTC SINOVATE SOFTWARE CO.LTD All Rights Reserved.
 */

package com.cmcc.zysoft.infocollection.service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.cmcc.zysoft.infocollection.constant.URLConstant;
import com.cmcc.zysoft.infocollection.dao.ResourcePcDao;
import com.cmcc.zysoft.infocollection.model.Resource;
import com.starit.common.dao.hibernate.HibernateBaseDao;
import com.starit.common.dao.service.BaseServiceImpl;

/**
 * @author 袁凤建
 * <br />邮箱: yuan.fengjian@ustcinfo.com
 * <br />描述: ResourcePcService.java
 * <br />版本: 1.0.0
 * <br />日期: 2013-8-26 上午9:34:34
 * <br />CopyRight © 2012 USTC SINOVATE SOFTWARE CO.LTD All Rights Reserved.
 */

@Service
public class ResourcePcService extends BaseServiceImpl<Resource, String> {

	/**
	 * 删除商户信息URL.
	 */
	@Value("${remove.shop.url}")
	private String removeShopUrl;
	
	@javax.annotation.Resource
	private ResourcePcDao resourcePcDao;
	
	@Override
	public HibernateBaseDao<Resource, String> getHibernateBaseDao() {
		return this.resourcePcDao;
	}
	
	/**
	 * 获取所有入库状态为入库等待(state=1)或入库中(state=2)的资源信息.
	 * @return List<Resource>
	 */
	public List<Resource> getResourceList() {
		return this.resourcePcDao.getResourceList();
	}
	
	/**
	 * 根据流水号查询商户信息.
	 * @param infoId 流水号
	 * @return Resource
	 */
	public Resource getResourceByInfoId(String infoId) {
		List<Resource> list = this.resourcePcDao.getResourceByInfoId(infoId);
		if(!list.isEmpty()) {
			return list.get(0);
		} else {
			return null;
		}
	}
	
	/**
	 * 获取资源分页列表信息.
	 * @param provinceId 省份ID
	 * @param cityId 城市ID
	 * @param channelId 频道ID
	 * @param checkFlag 是否经过审核(0-是,1-否)
	 * @param dataFlag 数据标识(0-新增,1-更新)
	 * @param shopName 商户名称
	 * @param startTime 开始时间
	 * @param endTime 结束时间
	 * @param page 页码
	 * @param rows 每页记录数
	 * @return Map<String, Object>
	 */
	public Map<String, Object> resourcePage(String provinceId, String cityId, String channelId, String checkFlag, String dataFlag, 
			String shopName, String startTime, String endTime, int page, int rows) {
		return this.resourcePcDao.resourcePage(provinceId, cityId, channelId, checkFlag, dataFlag, shopName, startTime, endTime, page, rows);
	}
	
	/**
	 * 用户使用情况统计.
	 * @param companyId 企业ID
	 * @param departmentId 部门ID
	 * @param keyword 搜索关键字(用户姓名/手机号)
	 * @param startTime 开始时间
	 * @param endTime 结束时间
	 * @param page 页码
	 * @param rows 每页记录数
	 * @return Map<String, Object>
	 */
	public Map<String, Object> statisticInfo(String companyId, String departmentId, String keyword, String startTime, String endTime, int page, int rows) {
		return this.resourcePcDao.statisticInfo(companyId, departmentId, keyword, startTime, endTime, page, rows);
	}
	
	/**
	 * 企业统计详细信息.
	 * @param companyId 企业ID
	 * @param startTime 开始时间
	 * @param endTime 结束时间
	 * @param page 页码
	 * @param rows 每页记录数
	 * @return Map<String, Object>
	 */
	public Map<String, Object> companyStatInfo(String companyId, String startTime, String endTime, int page, int rows) {
		return this.resourcePcDao.companyStatInfo(companyId, startTime, endTime, page, rows);
	}
	
	/**
	 * 部门统计详细信息.
	 * @param companyId 企业ID
	 * @param startTime 开始时间
	 * @param endTime 结束时间
	 * @return List<Map<String, Object>>
	 */
	public List<Map<String, Object>> deptStatInfo(String companyId, String startTime, String endTime) {
		List<Map<String, Object>> list = this.resourcePcDao.deptStatInfo("0", companyId, startTime, endTime);
		return this.childDept(list, companyId, startTime, endTime);
	}
	
	/**
	 * 递归获取子部门信息.
	 * @param list 父部门列表
	 * @param companyId 企业ID
	 * @param startTime 开始时间
	 * @param endTime 结束时间
	 * @return List<Map<String, Object>>
	 */
	public List<Map<String, Object>> childDept(List<Map<String, Object>> list, String companyId, String startTime, String endTime) {
		for(Map<String, Object> map : list) {
			String haveChildDeparment = map.get("have_child_deparment").toString();
			if("Y".equals(haveChildDeparment)) {
				String parentDepartmentId = map.get("department_id").toString();
				List<Map<String, Object>> childList = this.resourcePcDao.deptStatInfo(parentDepartmentId, companyId, startTime, endTime);
				this.childDept(childList, companyId, startTime, endTime);
				map.put("children", childList);
				map.put("state", "closed");
			} else {
				map.put("state", "open");
			}
		}
		return list;
	}
	
	/**
	 * 获取采集信息新增、修改统计次数.
	 * @return List<Map<String,Object>>
	 */
	public List<Map<String, Object>> getResourceCount() {
		return this.resourcePcDao.getResourceCount();
	}
	
	
	/**
	 * 获取采集信息新增、修改各地市总次数.
	 * @return List<Map<String,Object>>
	 */
	public List<Map<String, Object>> getResourceSumCount() {
		return this.resourcePcDao.getResourceSumCount();
	}
	
	/**
	 * 每月采集和更新商户信息统计.
	 * @return String
	 */
	public String infoAnalyze() {
		String Mon1 = "month1";
		String Mon2 = "month2";
		String Mon3 = "month3";
		String Mon4 = "month4";
		String Mon5 = "month5";
		String Mon6 = "month6";
		String Mon7 = "month7";
		String Mon8 = "month8";
		String Mon9 = "month9";
		String Mon10 = "month10";
		String Mon11 = "month11";
		String Mon12 = "month12";
		//获取采集信息新增、修改统计次数.
		List<Map<String, Object>> list = this.resourcePcDao.getResourceCount();
		//封装统计结果.
		String json = "{tooltip : {trigger : 'axis'}, legend : {data : ['新增信息', '更新信息']}, ";
		json +="toolbox : {show : true, "+
			   "feature : {mark : true, dataView : {readOnly : false}, "+
					"magicType : ['line', 'bar'], "+
					"restore : true, "+
					"saveAsImage : false}}, ";
		json +=	"calculable : true, ";
		json += "xAxis : [{type : 'category', data : ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']}], ";
		json += "yAxis : [{type : 'value', splitArea : {show : true}}],";
		json += "series : [{name : '新增信息', type : 'bar', data : [ ";
		json += list.get(0).get(Mon1) + "," + list.get(0).get(Mon2) + "," + list.get(0).get(Mon3) + "," + 
				list.get(0).get(Mon4) + "," + list.get(0).get(Mon5) + "," + list.get(0).get(Mon6) + "," + 
				list.get(0).get(Mon7) + "," + list.get(0).get(Mon8) + "," + list.get(0).get(Mon9) + "," + 
				list.get(0).get(Mon10) + "," + list.get(0).get(Mon11) + "," + list.get(0).get(Mon12) + "]}, ";
		json += "{name : '更新信息', type : 'bar', data : [ ";
		json += list.get(1).get(Mon1) + "," + list.get(1).get(Mon2) + "," + list.get(1).get(Mon3) + "," + 
				list.get(1).get(Mon4) + "," + list.get(1).get(Mon5) + "," + list.get(1).get(Mon6) + "," + 
				list.get(1).get(Mon7) + "," + list.get(1).get(Mon8) + "," + list.get(1).get(Mon9) + "," + 
				list.get(1).get(Mon10) + "," + list.get(1).get(Mon11) + "," + list.get(1).get(Mon12) + "]}]}";
		return json;
	}
	
	/**
	 * 各地市商户信息采集情况汇总.
	 * @return String
	 */
	public String infoSumAnalyze() {
		String[] arr = {"六安市", "安庆市", "滁州市", "宣城市", "阜阳市", "宿州市", "黄山市", "巢湖市", "亳州市", "池州市", 
				"合肥市", "蚌埠市", "芜湖市", "淮北市", "淮南市", "马鞍山市", "铜陵市"};	
		//获取采集信息新增、修改各地市总次数.
		List<Map<String,Object>> list = this.resourcePcDao.getResourceSumCount();
		String json = "{tooltip : {trigger : 'item'}, legend : {orient : 'vertical', x : 'right' , data : ['汇总数据']}, "+
				"dataRange : {min : 0, max : 1000, color : ['orange', 'yellow'], text : ['高', '低'], calculable : true}, "+
				"series : [{name : '汇总数据', type : 'map', mapType : '安徽', selectedMode : 'single', "+
				"itemStyle : {normal : {label : {show : true}}, emphasis : {label : {show : true}}}, "+
				"data : [ ";
			for(int i=0;i<arr.length;i++){
				json += "{name : '" + arr[i] + "', value : " + list.get(0).get(arr[i]) + "} ";
				if (i < arr.length - 1) {
					json += ",";
				}	
			}
			json += "]}]}";
		return json;
	}
	
	/**
	 * 根据资源ID(逻辑)删除商户信息.
	 * @param resourceId 资源ID
	 * @return String
	 */
	@Transactional
	public String removeLocal(String resourceId) {
		try {
			//根据资源ID获取资源信息
			Resource resource = this.resourcePcDao.get(resourceId);
			resource.setDelFlag("1");
			this.resourcePcDao.update(resource);
			return "SUCCESS";
		} catch (Exception e) {
			e.printStackTrace();
			return "ERROR";
		}
	}
	
	/**
	 * 根据资源ID(逻辑)删除商户信息-先删中央库数据,再本地数据.
	 * @param resourceId 资源ID
	 * @return String
	 */
	/*@Transactional
	public String removeLocal(String resourceId) {
		String result = "";
		try {
			Resource resource = this.resourcePcDao.get(resourceId);
			//删除中央库的商户信息
			String response = removeCenter(resource.getShopId());
			System.out.println("=======================================================================");
			System.out.println("response : " + response);
			System.out.println("=======================================================================");
			if(StringUtils.hasText(response)) {
				//解析中央库返回的json数据
				JSONObject object = JSONObject.parseObject(response);
				//中央信息库中商户信息删除成功,逻辑删除本地数据
				if("1".equals(object.get("status").toString())) {
					resource.setDelFlag("1");
					this.resourcePcDao.update(resource);
					result = "SUCCESS";
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			result = "ERROR";
		}
		return result;
	}*/
	
	/**
	 * 根据商户ID将中央库中的商户删除.
	 * @param shopId 商户ID
	 * @return String(中央库返回报文)
	 */
	public String removeCenter(String shopId) {
		String dataSource = URLConstant.DATA_SOURCE;
		String url = String.format(removeShopUrl, shopId, dataSource);
		
		System.out.println("=======================================================================");
		System.out.println("删除商户URL : " + removeShopUrl);
		System.out.println("拼接后url   : " + url);
		System.out.println("=======================================================================");
		
		HttpClient httpClient = new HttpClient();
		httpClient.getParams().setAuthenticationPreemptive(true);
		//创建POST方法的实例
		PostMethod postMethod = new PostMethod(url);
		//使用系统提供的默认的恢复策略
		postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
		String result = ""; //初始化返回结果(String类型)
		try {
			//执行getMethod
			int statusCode = httpClient.executeMethod(postMethod);
		    if (statusCode != HttpStatus.SC_OK) {
			    System.err.println("Method failed: " + postMethod.getStatusLine());
		    }
		    result = postMethod.getResponseBodyAsString();
		} catch (IOException e) {
		   e.printStackTrace();
		} finally {
			//释放连接
			postMethod.releaseConnection();
		}
		return result;
	}
}